package com.cindata

import com.cindata.dictionary.*
import grails.transaction.Transactional
import net.sf.json.JSON
import org.apache.poi.hssf.usermodel.HSSFWorkbook
import org.apache.poi.ss.formula.functions.T
import org.grails.plugins.excelimport.AbstractExcelImporter
import org.springframework.security.access.annotation.Secured

import java.text.SimpleDateFormat
import static org.springframework.http.HttpStatus.*

@Secured(['isAuthenticated()'])
@Transactional
class EstateImportBatchController
{

    static allowedMethods = [save: "POST", update: "PUT", delete: "DELETE"]
    def evaluateService
    def excelExportService
    def sessionFactory
    def springSecurityService
    def componentService

    def index(Integer max)
    {
        params.max = Math.min(max ?: 10, 100)
        def order = params["order"]
        def sort = params["sort"]
        String sql = " from EstateImportBatch e where 1=1"
        def user = User.findById(springSecurityService.principal.id)
        def accountSql = Account.FilterAccountSql(user)
        if (accountSql)
        {
            sql += " and e.createBy.account.id in ${accountSql}"
        }

        String sql1 = "select count(e.id) " + sql
        if (order && sort)
        {
            sql += " order by e.${sort} ${order}"
        }
        else
        {
            sql += " order by e.modifiedDate desc "
        }
        def estateImportBatchList = EstateImportBatch.executeQuery(sql, [max: params.max ?: 10, offset: params.offset ?: 0])
        def estateImportBatchCount = EstateImportBatch.executeQuery(sql1)

        respond EstateImportBatch, model: [estateImportBatchList: estateImportBatchList, estateImportBatchCount: estateImportBatchCount[0]]
    }

    def show(EstateImportBatch estateImportBatch)
    {
        respond estateImportBatch
    }

    @Transactional
    def ajaxSearch()
    {
        def batchs = params["batchs"]
        def result = false
        def sql = "from EstateImportBatch e where 1=1 "
        def user = User.findById(springSecurityService.principal.id)
        def accountSql = Account.FilterAccountSql(user)
        if (accountSql)
        {
            sql += " and e.createBy.account.id in ${accountSql}"
        }
        if (batchs)
        {
            sql += " and e.batchNumber = '${batchs}' "
        }
        def batchList = EstateImportBatch.executeQuery(sql).asList()
        if (batchList.size() != 0)
        {
            result = true
        }
        else
        {
            result = false
        }
        render([result: result] as JSON)
    }

    @Transactional
    def searchEstate()
    {
        def order = params["order"]
        def sort = params["sort"]
        def batchs = params["batchs"]
        //批次号
        def createBy = params["createBy"]
        //导入经手人
        def status = params['status']
        //导入状态
        def evaluateType = params['evaluateType']
        //处理方式
        def startDate = params["startDate"]
        //开始时间
        def endDate = params["endDate"]
        //结束时间
        def importFileType = params["importFileType"]
        def sqlParam = [:]
        //导入文件类型
        String sql = "from EstateImportBatch e where 1=1"
        def user = User.findById(springSecurityService.principal.id)
        def accountSql = Account.FilterAccountSql(user)
        if (accountSql)
        {
            sql += " and e.createBy.account.id in ${accountSql}"
        }
        if (batchs)
        {
            sql += " and e.batchNumber like '%${batchs}%'"
        }
        if (status)
        {
            sql += " and e.status.name = '${status}'"
        }
        if (evaluateType)
        {
            sql += " and e.evaluateType.id= '${evaluateType}'"
        }
        if (startDate && endDate)
        {
            //中文日期转换
            sqlParam.startDate = DateUtil.GetDateBeginByDateStr(startDate.toString())
            sqlParam.endDate = DateUtil.GetNextDateBeginByDateStr(endDate.toString())
            sql += "and e.createdDate >= :startDate and e.createdDate  < :endDate "
        }
        if (createBy)
        {
            sql += "and e.createBy.id = '${createBy}'"
        }
        if (importFileType)
        {
            sql += "and e.importFileType.id = '${importFileType}'"
        }

        //查询总数
        String countSql = "select count(e.id) " + sql

        if (order && sort)
        {
            sql += " order by e.${sort} ${order}"
        }
        else
        {
            sql += "order by e.modifiedDate desc "
        }
        //执行查询方法
        def estateImportBatchList = EstateImportBatch.executeQuery(sql, sqlParam, [max: params.max ?: 10, offset: params.offset ?: 0])
        def count = EstateImportBatch.executeQuery(countSql, sqlParam)
        if (estateImportBatchList != null)
        {

            respond EstateImportBatch, model: [estateImportBatchList: estateImportBatchList, estateImportBatchCount: count[0], params: params], view: 'index'
        }
        else
        {
            respond EstateImportBatch, view: 'index'
        }
        // println(estateImportList.get(0))
        //        println(estateImportList.get(0).getCreateBy().username)
    }

    def create()
    {
        respond new EstateImportBatch(params)
    }

    @Transactional
    def excelImport()
    {
        /**
         * 读取文件*/
        def file = request.getFile('myFile')
        def iftCode = params["importFileType"]
        //将文件传给对应类,读取文件
        AbstractExcelImporter importer
        if (iftCode == "Estate")
        {
            importer = new EstateExcelImporter()
        }
        else if (iftCode == "Repayment")
        {
            importer = new RepaymentExcelImporter()
        }
        importer.read(file.getInputStream())
        def estateMapList = importer.getEstates()
        importer.ge

        //获取集合
        def estateNum = estateMapList.size()

        def batch = params["batch"]

        def createBy = User.findByUsername(sec.loggedInUserInfo(field: "username"))
        def currentDate = new Date()
        def importFileType = ImportFileTypeDict.findByCode(iftCode)
        /**
         * 加入批次信息*/
        Map param = [batchNumber: batch,
            importFileType: importFileType,
            estateNum: estateNum,
            matchNum: 0,
            status: ExecStatusDict.EXECUTING(),
            createBy: createBy,
            isDeleted: 0]

        def newImportBatch = new EstateImportBatch(param)

        //将批次信息加入批次表中
        if (!newImportBatch.save())
        {
            println "EstateImportBatch not saved, errors = ${newImportBatch.errors}"
            respond EstateImportBatch, model: ["message": "导入失败", "success": false], view: "message"
        }

        println '批次ID: [${newEstateImportBatch.id}]'


        /**
         * 遍历存入excel里的数据*/
        Thread.start {
            evaluateService.batchInserts(estateMapList, newImportBatch, currentDate)
            if (iftCode == 'estate')
            {
                // 如果是押品导入才开始评估
                evaluateService.evaluateBatch(newImportBatch.getId())
            }
        }
        respond EstateImportBatch, model: ["success": true, "key": newImportBatch.id], view: "message"
        return
    }

    @Transactional
    def csvImport()
    {
        /**
         * 读取文件*/
        def file = request.getFile('myFile')
        def fileCharset = FileUtil.GetFileCharset(file.getInputStream())
        def iftCode = params["importFileType"]
        def evaluateType = params["evaluateType"]

        //将文件传给对应类,读取文件
        def importer
        if (iftCode == "Estate")
        {
            importer = new EstateCSVImporter()
        }
        else if (iftCode == "Repayment")
        {
            importer = new RepaymentCSVImporter()
        }
        def estateMapList = importer.read(file.getInputStream(), fileCharset)

        //获取集合
        def estateNum = estateMapList.size()

        def sdf = new SimpleDateFormat("yyyyMMddHHmmss")
        def batch = sdf.format(new Date())

        def createBy = User.findByUsername(sec.loggedInUserInfo(field: "username"))
        def currentDate = new Date()
        def importFileType = ImportFileTypeDict.findByCode(iftCode)

        def evaluateTypeTemp
        if (evaluateType == "1")
        {
            evaluateTypeTemp = EvaluateDict.AUTOMATIC()
        }
        if (evaluateType == "7")
        {
            evaluateTypeTemp = EvaluateDict.ARTIFICIAL()
        }
        if (evaluateType == "8")
        {
            evaluateTypeTemp = EvaluateDict.AUTOANDARTIFICIAL()
        }

        /**
         * 加入批次信息*/
        Map param = [batchNumber: batch,
            importFileType: importFileType,
            estateNum: estateNum,
            matchNum: 0,
            status: ExecStatusDict.EXECUTING(),
            createBy: createBy,
            isDeleted: 0,
            evaluateType: evaluateTypeTemp,
            type: '导入']

        def newImportBatch = new EstateImportBatch(param)

        //将批次信息加入批次表中
        if (!newImportBatch.save())
        {
            println "EstateImportBatch not saved, errors = ${newImportBatch.errors}"
            respond EstateImportBatch, model: ["message": "导入失败", "success": false], view: "message"
        }

        println '批次ID: [' + newImportBatch?.id + "]"

        /**
         * 遍历存入excel里的数据*/
        Thread.start {
            evaluateService.batchInserts(estateMapList, newImportBatch, currentDate)
            if (iftCode == 'Estate')
            {
                // evaluateType  1 : 自动， 7： 人工 8：自动加人工
                evaluateService.evaluateBatch(newImportBatch.getId(), evaluateType?.toInteger())
            }
        }
        respond EstateImportBatch, model: ["success": true, "key": newImportBatch.id], view: "message"
        return
    }

    def getProgress(Long progressKey)
    {
        def progress = evaluateService.getProgress(progressKey)
        render([progress: progress] as grails.converters.JSON)
    }

    @Transactional
    def save(EstateImportBatch estateImportBatch)
    {
        if (estateImportBatch == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (estateImportBatch.hasErrors())
        {
            transactionStatus.setRollbackOnly()
            respond estateImportBatch.errors, view: 'create'
            return
        }

        estateImportBatch.save flush: true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.created.message', args: [message(code: 'estateImportBatch.label', default: 'EstateImportBatch'), estateImportBatch.id])
                redirect estateImportBatch
            }
            '*' { respond estateImportBatch, [status: CREATED] }
        }
    }

    def exportFailureEstate(Long id)
    {
        //根据批次ID导出失败数据
        def batch = EstateImportBatch.findById(id)
        String sql = "from EstateImport where batch.id = " + batch.id + " and evaluateStatue.name = '失败'"
        def result = EstateImport.executeQuery(sql)
        //导出数据
        response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode("处理失败押品", "UTF-8") + ".xls")
        response.contentType = "application/x-rarx-rar-compressed"
        ExcelExportService excelExportService = new ExcelExportService()
        //提前还款情况报表
        String[] headers = ["押品编号", "押品状态", "城市名称", "行政区名称", "地址", "面积（平方米）",
            "总楼层", "当前层", "贷款合同号", "处理状态", "失败原因"]
        String[] params = ["externalId", "estateStatus", "cityName", "districtName", "address", "buildArea",
            "totalFloor", "currentFloor", "contractNo", "status", "failReason"]
        List<Map<String, T>> listn = new ArrayList<Map<String, T>>();
        result.each {
            print(it.evaluateStatue.name)
            Map<String, T> m = new HashMap<String, T>();
            m.put("externalId", it?.externalId)
            m.put("estateStatus", it?.estateStatus?.name)
            m.put("cityName", it?.cityName)
            m.put("districtName", it?.districtName)
            m.put("address", it?.address)
            m.put("buildArea", it?.buildArea)

            m.put("totalFloor", it?.totalFloor)
            m.put("currentFloor", it?.currentFloor)
            m.put("contractNo", it?.contractNo)
            m.put("status", "失败")
            m.put("failReason", it?.failReason)

            listn.add(m)
        }
        HSSFWorkbook workbook = excelExportService.exportExcel("处理失败押品", headers, listn, params);
        workbook.write(response.getOutputStream());
        response.flushBuffer() //立即清空输出
        response.getOutputStream().close();
        println("下载完成")
    }

    def edit(EstateImportBatch estateImportBatch)
    {
        respond estateImportBatch
    }

    @Transactional
    def update(EstateImportBatch estateImportBatch)
    {
        if (estateImportBatch == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (estateImportBatch.hasErrors())
        {
            transactionStatus.setRollbackOnly()
            respond estateImportBatch.errors, view: 'edit'
            return
        }

        estateImportBatch.save flush: true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.updated.message', args: [message(code: 'estateImportBatch.label', default: 'EstateImportBatch'), estateImportBatch.id])
                redirect estateImportBatch
            }
            '*' { respond estateImportBatch, [status: OK] }
        }
    }

    @Transactional
    def delete(EstateImportBatch estateImportBatch)
    {

        if (estateImportBatch == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        estateImportBatch.delete flush: true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.deleted.message', args: [message(code: 'estateImportBatch.label', default: 'EstateImportBatch'), estateImportBatch.id])
                redirect action: "index", method: "GET"
            }
            '*' { render status: NO_CONTENT }
        }
    }

    protected void notFound()
    {
        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.not.found.message', args: [message(code: 'estateImportBatch.label', default: 'EstateImportBatch'), params.id])
                redirect action: "index", method: "GET"
            }
            '*' { render status: NOT_FOUND }
        }
    }

    // 失败押品转人工
    @Transactional
    def evaluateFailureEstate(Long id)
    {
        evaluateService.evaluateFailureEstate(id)

        def estateImportBatch = EstateImportBatch.findById(id)
        estateImportBatch.evaluateType = EvaluateDict.AUTOANDARTIFICIAL()
        estateImportBatch.save flush: true

        redirect action: 'index'
    }

    def evaluateAccountBatchIndex()
    {
        def user = User.findById(springSecurityService.principal.id)
        def sql = "from EstateImportBatch e where e.latestEvaluateAccount.id = ${user.account?.id}"
        def batch = params['batchName']
        if (batch) 
        {
            sql += " and e.batchNumber like '%${batch}%'"
        }
        def status = params['status']
        if (status)
        {
            sql += " and e.status.name = '${status}'"
        }
        def countSql = "select count(e.id) " + sql
        sql += " order by e.modifiedDate desc"
        
        def estateImportBatchList = EstateImportBatch.executeQuery(sql, [max: params.max ?: 10, offset: params.offset ?: 0])
        def estateImportBatchCount = EstateImportBatch.executeQuery(countSql)
        respond EstateImportBatch, model: [estateImportBatchList: estateImportBatchList, estateImportBatchCount: estateImportBatchCount[0], params: params]
    }

    // 评估机构下载文件
    def evaluateAccountBatchExport(Long id)
    {
        def batch = EstateImportBatch.findById(id)
        String sql = "select estate.externalId, estate.buildingType.name, estate.estateStatus.name, estate.city.name, estate.district.name, estate.sourceAddress, estate.sourceBuildArea, estate.sourceTotalFloor, estate.sourceCurrentFloor from BatchEstate where batch.id = " + batch.id
        def list = EstateImport.executeQuery(sql)
        
        def listTitle = new ArrayList<Map>(Arrays.asList("押品编号", "房屋用途", "押品状态", "城市名称", "行政区名称", "地址", "面积（平方米）", "总楼层", "当前层", "最新评估价值", "最新评估日期"))
        response.setContentType("text/csv")
        response.setContentType("application/csv;charset=UTF-8")
        response.setHeader("Content-Disposition", "attachment;FileName=${batch?.batchNumber}.csv")
        OutputStream out = null
        try
        {
            out = response.getOutputStream()
        }
        catch (Exception e)
        {
            e.printStackTrace()
        }
        excelExportService.exportExcelData(out, listTitle, list)
        return null
    }

    // 评估机构上传文件
    def evaluateAccountBatchImport()
    {
        def batchNumber = params['batchNumberValue']
        def file = request.getFile('myFile')
        def fileOrgName = file?.getOriginalFilename()
        def fileType = fileOrgName?.split('\\.')[-1]
        fileType = fileType?.toLowerCase()

        File fileImage = new File(servletContext.getRealPath("/"), "images/${batchNumber}.${fileType}")
        file.transferTo(fileImage)

        respond EstateImportBatch, model: ["success": true, "key": "evaluateAccountBatchImport"], view: "message"
    }

    // 银行机构导入
    def bankAccountBatchImport(EstateImportBatch estateImportBatch)
    {
        def batchNumber = estateImportBatch?.batchNumber
        def webRootDir = servletContext.getRealPath("/")
        File file = new File(webRootDir, "images/${batchNumber}.csv")
        if (file.exists() && file.isFile())
        {
            BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), "GBK"))
            br.readLine()
            String line = null
            FileOutputStream fs = new FileOutputStream(new File(webRootDir + "logs/" + batchNumber + ".log"));
            PrintStream p = new PrintStream(fs);
            def st = 0
            def inquote = false
            def count = 0
            StringBuffer readLine = new StringBuffer()
            try
            {
                while ((line = br.readLine()) != null)
                {
                    readLine.append(line)
                    def maxPosition = readLine.length()
                    while (st < maxPosition)
                    {
                        def ch = readLine.charAt(st)
                        if (inquote && ch == ',')
                        {
                            readLine.setCharAt(st, (char) '，')
                        }
                        if (ch == '"')
                        {
                            inquote = !inquote
                        }
                        st++
                    }

                    line = readLine.toString()
                    def splitByDoubleQuotes = line.split('"')
                    def countDoubleQuotes = 0
                    if (line.charAt(line.length() - 1) == '"')
                    {
                        countDoubleQuotes = splitByDoubleQuotes.length
                    }
                    else
                    {
                        countDoubleQuotes = splitByDoubleQuotes.length - 1
                    }
                    if (countDoubleQuotes % 2 == 1)
                    {
                        continue
                    }
                    else
                    {
                        readLine.setLength(0)
                        st = 0
                    }

                    def list = line.split(",")
                    count++
                    if (list)
                    {
                        def estate = Estate.findByExternalId(list[0])
                        def batchEstate = BatchEstate.findByEstateAndBatch(estate, estateImportBatch)
                        if (batchEstate) 
                        {
                            batchEstate.evaluateDate = Date.parse("yyyy/MM/dd", list[10])
                            batchEstate.evaluateStatue = ExecStatusDict.SUCCESS()
                            if (batchEstate.validate()) 
                            {
                                batchEstate.save flush: true    
                            }
                            else
                            {
                                println batchEstate.errors
                            }
                        }
                        
                        if (estate) 
                        {
                            estate.totalPrice = new BigDecimal(list[9])
                            estate.latestEvaluatePrice = new BigDecimal(list[9])
                            estate.valuationDate = Date.parse("yyyy/MM/dd", list[10])
                            estate.latestEvaluateDate = Date.parse("yyyy/MM/dd", list[10])
                            estate.latestEvaluateAccount = batchEstate.latestEvaluateAccount
                            if (estate.firstEvaluatePrice) 
                            {
                                estate.priceFluctuationsRatio = (estate.latestEvaluatePrice - estate.firstEvaluatePrice) / estate.firstEvaluatePrice
                            }
                            else
                            {
                                estate.firstEvaluatePrice = estate.latestEvaluatePrice
                            }
                            if (estate.validate()) 
                            {
                                estate.save flush: true
                            }
                            else
                            {
                                println estate.errors
                            }

                            ValuationHistory valuationHistory = new ValuationHistory()
                            valuationHistory.name = estate?.communityName
                            valuationHistory.valuationDate = estate?.latestEvaluateDate
                            valuationHistory.unitPrice = estate?.unitPrice
                            valuationHistory.totalPrice = estate?.totalPrice
                            valuationHistory.sourceId = estate?.id
                            valuationHistory.sourceClass = "estate"
                            valuationHistory.evaluateStatus = ExecStatusDict.SUCCESS()
                            valuationHistory.evaluateType = EvaluateDict.EVALUATE()
                            valuationHistory.save(flush: true)
                        }
                    }
                    else
                    {
                        println "not list"
                    }
                }
            }
            catch (Exception e)
            {
                log.info "file read wrong"
                p.println("file read wrong")
            }
            finally
            {
                if (br != null)
                {
                    try
                    {
                        br.close()
                        br = null
                    }
                    catch (IOException e)
                    {
                        e.printStackTrace()
                    }
                }
                log.info "file read success!!!"
                p.println("导入完成，本次导入订单总数: " + count)
                p.println("file read success!!!")
            }
            p.close()

            // 修改批次表
            estateImportBatch.status = ExecStatusDict.SUCCESS()
            estateImportBatch.matchNum = count
            estateImportBatch.save flush: true
        }
        else
        {
            println "对不起，文件不存在！"
            flash.message = "对不起，文件不存在！"
        }

        redirect action: "index"
    }

    def estateImportBatchShow(EstateImportBatch estateImportBatch)
    {
        def max = Math.min(params.max ? params.max.toInteger() : 10, 100)
        def offset = params.offset ? params.offset.toInteger() : 0

        def batchEstateList = BatchEstate.findAllByBatch(estateImportBatch, [max: max, offset: offset])
        respond estateImportBatch, model: [batchEstateList: batchEstateList, batchEstateCount: BatchEstate.countByBatch(estateImportBatch)]
    }

    def estateImportBatchEdit(EstateImportBatch estateImportBatch)
    {
        params['targetUri'] = request.getHeader("referer")
        respond estateImportBatch
    }

    @Transactional
    def estateImportBatchUpdate(EstateImportBatch estateImportBatch)
    {
        if (estateImportBatch == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (estateImportBatch.hasErrors())
        {
            transactionStatus.setRollbackOnly()
            respond estateImportBatch.errors, view: 'estateImportBatchEdit'
            return
        }

        estateImportBatch.save flush: true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.created.message', args: [message(code: 'estateImportBatch.label', default: 'EstateImportBatch'), estateImportBatch.id])
                redirect url: params['targetUri']
            }
            '*' { respond estateImportBatch, [status: CREATED] }
        }
    }

    def estateBatchReValuation(EstateImportBatch estateImportBatch)
    {
        // 更显批次状态为执行中
        estateImportBatch.status = ExecStatusDict.EXECUTING()
        estateImportBatch.matchNum = 0
        estateImportBatch.save flush: true

        def evaluateType = estateImportBatch?.evaluateType
        if (!evaluateType)
        {
            flash.message = "请选择评估方式"
            redirect action: 'estateImportBatchShow', id: estateImportBatch?.id
            return
        }

        if (evaluateType == EvaluateDict.AUTOMATIC())
        {
            evaluateType = 1
        } 
        if (evaluateType == EvaluateDict.ARTIFICIAL())
        {
            evaluateType = 7
        } 
        if (evaluateType == EvaluateDict.AUTOANDARTIFICIAL())
        {
            evaluateType = 8
        }
        if (evaluateType == EvaluateDict.EVALUATE())
        {
            def batchAccountCount = BatchAccount.countByBatch(estateImportBatch)
            if (batchAccountCount == 0)
            {
                flash.message = "请选择评估机构"
                redirect action: 'estateImportBatchShow', id: estateImportBatch?.id
                return
            }
            if (batchAccountCount > 1 && !estateImportBatch?.distributeRule)
            {
                flash.message = "请选择评估分发策略"
                redirect action: 'estateImportBatchShow', id: estateImportBatch?.id
                return
            }
            evaluateType = 10
        }

        // 重估
        if (evaluateType != 10)
        {
            Thread.start
            {
                evaluateService.estateBatchReEvaluation(estateImportBatch.getId(), evaluateType)
            }

            redirect controller: 'estateImportBatch', action: 'index'
            return
        }
        else
        {
            // 评估机构重估
            // 评估策略
            def latestEvaluateAccount = null
            def accounts = BatchAccount.findAllByBatch(estateImportBatch)*.account
            if (accounts?.size() == 1) 
            {
                latestEvaluateAccount = accounts[0]
            }
            else
            {
                def serviceParams = [estateImportBatch: estateImportBatch]
                def distributeRule = estateImportBatch.distributeRule
                println distributeRule
                println serviceParams

                latestEvaluateAccount = componentService.evaluate(distributeRule, serviceParams)
            }

            estateImportBatch.latestEvaluateAccount = latestEvaluateAccount
            estateImportBatch.evaluateType = EvaluateDict.EVALUATE()
            estateImportBatch.status = ExecStatusDict.EXECUTING()
            estateImportBatch.matchNum = 0
            if (estateImportBatch.validate()) 
            {
                estateImportBatch.save flush: true
            }
            else
            {
                println estateImportBatch.errors
            }

            def batchEstateList = BatchEstate.findAllByBatch(estateImportBatch)
            batchEstateList?.each
            {
                it?.latestEvaluateAccount = latestEvaluateAccount
                it?.evaluateStatue = ExecStatusDict.EXECUTING()
            }
        }

        redirect controller: 'estateImportBatch', action: 'index'
    }

    def exportFailureBatchEstate(Long id)
    {
        //根据批次ID导出失败数据
        def batch = EstateImportBatch.findById(id)
        String sql = "from BatchEstate where batch.id = " + batch.id + " and evaluateStatue.name = '失败'"
        def result = BatchEstate.executeQuery(sql)
        //导出数据
        response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode("处理失败押品", "UTF-8") + ".xls")
        response.contentType = "application/x-rarx-rar-compressed"
        ExcelExportService excelExportService = new ExcelExportService()

        String[] headers = ["批次号", "押品编号", "押品状态", "城市名称", "行政区名称", "地址", "面积（平方米）", "总楼层", "当前层", "处理状态", "失败原因"]
        String[] params = ["batchNumber", "externalId", "estateStatus", "cityName", "districtName", "address", "buildArea", "totalFloor", "currentFloor", "status", "failReason"]
        List<Map<String, T>> listn = new ArrayList<Map<String, T>>();
        result.each {
            Map<String, T> m = new HashMap<String, T>();
            m.put("batchNumber", it?.batch?.batchNumber)
            m.put("externalId", it?.estate?.externalId)
            m.put("estateStatus", it?.estate?.estateStatus?.name)
            m.put("cityName", it?.estate?.city?.name)
            m.put("districtName", it?.estate?.district?.name)
            m.put("address", it?.estate?.sourceAddress)
            m.put("buildArea", it?.estate?.sourceBuildArea)
            m.put("totalFloor", it?.estate?.sourceTotalFloor)
            m.put("currentFloor", it?.estate?.sourceCurrentFloor)
            m.put("status", "失败")
            m.put("failReason", it?.failReason)

            listn.add(m)
        }
        HSSFWorkbook workbook = excelExportService.exportExcel("处理失败押品", headers, listn, params);
        workbook.write(response.getOutputStream());
        response.flushBuffer() //立即清空输出
        response.getOutputStream().close();
        println("下载完成")
    }
}